/*
 *
 */
package ch.gje.playios.communication;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Paires two WebSocket clients
 *
 * @author jannis
 */
public class WebSocketPairer {
    /**
     * List of unpaired clients, key is the pairing number and between 0 and 9999
     */
    private static Map<Integer, WebSocketClient> unpairedClients = new HashMap<Integer, WebSocketClient>();

    /**
     * Adds a client to the list and returns a pairing number
     * @param client the client to add
     * @return the pairing number
     */
    public synchronized static int addUnpairedClient(WebSocketClient client) {
        if (unpairedClients.size() == 1000) {
            throw new TooManyUnpairedClientsException();
        } else {
            int number;
            do {
                number = new Random().nextInt(9999);
            } while (unpairedClients.containsKey(number));
            unpairedClients.put(number, client);
            return number;
        }
    }

    /**
     * Returns a client from the list of unpaired clients and removes it from the list
     * @param number the clients number
     * @return the client
     */
    public synchronized static WebSocketClient getAndRemoveUnpairedClient(int number) {
        WebSocketClient client = unpairedClients.get(number);
        unpairedClients.remove(number);
        return client;
    }
}
